<?php

declare(strict_types=1);

namespace App\Command;

use Hyperf\Context\ApplicationContext;
use Hyperf\Contract\ConfigInterface;
use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Command\Annotation\Command;
use Hyperf\Command\Command as HyperfCommand;
use Hyperf\DbConnection\Db;
use Hyperf\Support\Filesystem\Filesystem;
use PHPUnit\Event\Runtime\PHP;
use function Hyperf\Support\env;

/**
 * 批量导入谷歌图片到产品文件中
 */
#[Command]
class SaveImageCommand extends HyperfCommand
{
    protected $logger;
    protected $config;

    public function __construct(StdoutLoggerInterface $logger, ConfigInterface $config)
    {
        $this->logger = $logger;
        $this->config = $config;

        // 定义命令行名称
        parent::__construct('save:image');
    }

    public function configure()
    {
        parent::configure();
        $this->setDescription('批量导入谷歌图片到产品文件中');
    }

    public function handle()
    {
        ini_set('memory_limit', '-1');
        $startTime = ceil(getMicrotime());
        $fs = new Filesystem();
        $csvDir = BASE_PATH . '/storage/ggimg_csv/';
        $this->line('1.验证目录' . $csvDir . '和分类表');
        if (!$fs->isDirectory($csvDir)) {
            $this->logger->error('没有找到' . $csvDir . '这个目录');
            return \Hyperf\Command\Command::FAILURE;
        }
        $dirs = $fs->directories($csvDir);
        if (empty($dirs)) {
            $this->logger->error($csvDir . '目录下没有产品库目录');
            return \Hyperf\Command\Command::FAILURE;
        }
        $dirCount = count($dirs);
        $files = [];
        $fileCount = 0;
        foreach ($dirs as $dir) {
            $pdb = strtoupper(pathinfo($dir, PATHINFO_BASENAME));
            $temp = $fs->files($dir);
            $files[$pdb] = $temp;
            $fileCount += count($temp);
        }
        if (empty($files)) {
            $this->logger->error($csvDir . '目录下没有csv文件');
            return \Hyperf\Command\Command::FAILURE;
        }

        $this->line('2.遍历文件导入数据,共有' . $dirCount . '个目录，' . $fileCount . '个文件');
        $sj = 0;
        $modelProduct = new \App\Model\Product();
        $tableProduct = $modelProduct::TABLE_NAME;
        $productDir = BASE_PATH . '/storage/products/';
        $pdirnum = env('PRODUCTDIR_NUM');
        foreach ($files as $pdb => $fileItems) {
            foreach ($fileItems as $file) {
                $c = 0;
                $filename = $file->getFilename();
                $filepath = $file->getRealPath();
                if (!str_ends_with($filename, '.csv')) {
                    continue;
                }
                $domain = str_replace(['keyword_dbi.', '.csv', '.upload.tmp'], '', $filename);
                $sj += 1;
                $this->line('  开始导入第' . $sj . '个-' . $filename);

                $fh = fopen($filepath, 'r');
                while (!feof($fh)) {
                    $line = fgetcsv($fh, 0, ',');
                    if ($line !== false && !empty($line[2])) {
                        preg_match('/\d+/', $line[0], $match);
                        $productId = intval($match[0]);
                        $images = $line[2];
                        $encoding = mb_detect_encoding($images, 'UTF-8, ISO-8859-1, GBK', true);
                        if (mb_detect_encoding($images, 'UTF-8', true) === false) {
                            $images = mb_convert_encoding($images, 'UTF-8', $encoding);
                        }
                        $check = Db::table($tableProduct)->where($modelProduct::DOMAIN, $domain)->where($modelProduct::PRODUCT_ID, $productId)->first();
                        if ($productId > 0 && !empty($images) && !is_null($check)) {
                            $pid = $check->{$modelProduct::ID};
                            // 找到对应目录
                            $subDir = ceil($pid / $pdirnum);
                            $productPath = $productDir . $subDir . '/' . $pid . '.txt';
                            $content = $fs->get($productPath);
                            if (file_exists($productPath) && !empty($content)) {
                                $productArray = explode("|||", $content);
                                // 0-domain,1-product_id,2-product_db,3-cate_name1,4-cate_name2,5-cate_slug1,6-cate_slug2,7-cate_id1,8-cate_id2,9-logo,10-market_price,11-price,12-title,13-intro,14-seo_title,15-$seoDesc
                                // 正常图片未进来时时16个
                                if (count($productArray) < 17) { //产品.txt 里还没添加 google采集图片
                                    $imageContent = '|||' . $images;
                                    $fs->append($productPath, $imageContent);

                                    // 更新产品表的图片，暂时不做，因为确实没用，都是取文件获取的
                                    $c++;
                                    if ($c % 1000 === 1) {
                                        echo $c . '-';
                                    }
                                }
                            }
                        }
                    }
                }
                fclose($fh);
                // 删除这个csv文件
            }
        }

        $endTime = ceil(getMicrotime());
        $huafei = $endTime - $startTime;

        $this->line('图片已经全部更新完成，共花费' . $huafei . '秒，程序退出');
        return \Hyperf\Command\Command::SUCCESS;
    }
}